package com.gsta.ifishery.netty.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义命名线程工厂 . <br>
 * 
 * @author hkb
 */
public class NameThreadFactory implements ThreadFactory {

    /**
     * 线程池编号
     */
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);

    /**
     * 线程组
     */
    private final ThreadGroup group;

    /**
     * 线程编号
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * 名称后缀
     */
    private final String namePrefix;

    /**
     * 构造命名线程工厂
     * 
     * @param name
     */
    private NameThreadFactory(String name) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        if (name == null || name.isEmpty()) {
            name = "pool";
        }
        namePrefix = name + "-" + POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    /**
     * 静态工厂方法
     * 
     * @param name
     */
    public static NameThreadFactory newNameThreadFactory(String name) {
        return new NameThreadFactory(name);
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}
